#include "VolumeControl.h"

VolumeController::VolumeController():
mContext(GUID_NULL),
mVolume(NULL),
mEnumerator(NULL),
mDevice(NULL)
{

}

VolumeController::~VolumeController()
{
	if (mVolume)
	{
		mVolume->Release();
		mVolume = 0;
	}

	if (mEnumerator)
	{
		mEnumerator->Release();
		mEnumerator = 0;
	}

	if (mDevice)
	{
		mDevice->Release();
		mDevice = 0;
	}
	CoUninitialize();
}

bool VolumeController::Init()
{
	CoInitialize(NULL);
	CoCreateGuid(&mContext);

	// Get enumerator for audio endpoint devices.
	CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, __uuidof(IMMDeviceEnumerator), (void**)&mEnumerator);

	if (mEnumerator)
	{
		mEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &mDevice);
		if (mDevice)
		{			
			mDevice->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, (void**)&mVolume);
		}
	}

	return mVolume != NULL;
}

float VolumeController::GetVolume()
{
	float volume = 0.f;

	if (mVolume)
	{
		mVolume->GetMasterVolumeLevelScalar(&volume);
	}

	return volume;
}

void VolumeController::SetVolume(float level)
{
	if (level > 1.f)
	{
		level = 1.f;
	}

	if (level < 0.f)
	{
		level = 0.f;
	}

	if (mVolume)
	{
		mVolume->SetMasterVolumeLevelScalar(level, &mContext);
	}
}